// pages/search-result/search-result.js
import { areaList } from '../../miniprogram_npm/miniprogram_npm/@vant/area-data/index'
const app = getApp() // 获取全局APP对象
const db = wx.cloud.database({
    env: 'work1-0g1b3grp436e9236'
})
const dayjs = require('../../miniprogram_npm/miniprogram_npm/dayjs/index')
import Notify from '../../miniprogram_npm/miniprogram_npm/@vant/weapp/notify/notify'

Page({
    /**
     * 页面的初始数据
     */
    data: {
        keyword: '',
        // 弹出操作控
        showCityPicker: false,
        areaList,
        pickCity: '全国',
        curCity: '未知',
        isGetCurCity: false,
        preCity: [],
        // 选择框
        dropdownOption1: [
            { text: '按需求量', value: 0 },
            { text: '需求量大', value: 1 },
            { text: '需求量小', value: 2 },
        ],
        dropdownOption2: [
            { text: '按截止日', value: 0 },
            { text: '最晚截止', value: 1 },
            { text: '最早截止', value: 2 },
        ],
        dropdownOption3: [
            { text: '按日薪', value: 0 },
            { text: '日薪最高', value: 1 },
            { text: '日薪最低', value: 2 },
        ],
        dropdownValue1: 0,
        dropdownValue2: 0,
        dropdownValue3: 0,
        orderBy: '',
        order: '',
        // 分页显示
        currentPage: 0,
        jobList: [],
        loading: true,
        isShowEndline: true
    },

    // 默认搜索
    async searchResult(orderBy='needNum', order='desc') {
        const _ = db.command
        // 参数设置
        let arr = [
            _.or({
                    category: db.RegExp({
                        regexp: this.data.keyword,
                        options: 'i',
                    })
                }, 
                {
                    jobName: db.RegExp({
                        regexp: this.data.keyword,
                        options: 'i',
                    })
                }),
        ]
        // 全国搜索和区域搜索
        if (this.data.pickCity.indexOf('全国') !== 0) {
            arr.push({
                location: db.RegExp({
                    regexp: this.data.pickCity,
                    options: 'i',
                }),
            })
        }
        let res = await db.collection('work_job').where({
            status: 1
        }).skip(this.data.currentPage * 10).limit(10)
            .orderBy(orderBy, order).where(_.and(arr)).get()
        await this.setJobList(res.data)
    },

    // 在搜索界面重新输入关键字进行搜索
    searchAgain(event) {
        this.setData({
            keyword: event.detail,
            loading: true,
            isShowEndline: true,
            jobList: [],
            currentPage: 0
        })
        this.searchResult().then(()=>{
            this.setData({
                loading: false
            })
        })
    },

    async setJobList(jobList) {
        // console.log(jobList)
        for (let i = 0; i < jobList.length; i++) {
            const job = jobList[i]
            jobList[i].endTime = dayjs(job.endTime).format("YYYY-MM-DD")
            const res = await db.collection('work_user').doc(job.userId).get()
            jobList[i].user = res.data
        }
        this.setData({
            jobList: this.data.jobList.concat(jobList)
        })
        if (this.data.jobList.length === 0) {
            this.setData({
                isShowEndline: false
            })
        }
        this.setData({loading: false})
    },

    // 按1搜索
    onSwitch1Change({ detail }) {
        this.setData({ dropdownValue1: detail, dropdownValue2: 0, dropdownValue3: 0})
        this.setData({
            loading: true,
            isShowEndline: true,
            jobList: [],
            currentPage: 0
        })
        // console.log(this.data.dropdownValue1)
        let order = 'asc'
        if (this.data.dropdownValue1 === 1) {
            order = 'desc'
        }
        this.setData({orderBy: 'needNum', order})
        // 为空，不搜索
        if(!this.data.isShowEndline) {
            this.setData({
                loading: false
            })
            return
        }
        this.searchResult('needNum', order).then(()=>{
            this.setData({
                loading: false
            })
        })
    },

    // 按2搜索
    onSwitch2Change({ detail }) {
        this.setData({ dropdownValue1: 0, dropdownValue2: detail, dropdownValue3: 0})
        this.setData({
            loading: true,
            isShowEndline: true,
            jobList: [],
            currentPage: 0
        })
        // console.log(this.data.dropdownValue2)
        let order = 'asc'
        if (this.data.dropdownValue2 === 1) {
            order = 'desc'
        }
        this.setData({orderBy: 'endTime', order})
        // 为空，不搜索
        if(!this.data.isShowEndline) {
            this.setData({
                loading: false
            })
            return
        }
        this.searchResult('endTime', order).then(()=>{
            this.setData({
                loading: false
            })
        })
    },

    // 按3搜索
    onSwitch3Change({ detail }) {
        this.setData({ dropdownValue1: 0, dropdownValue2: 0, dropdownValue3: detail})
        this.setData({
            loading: true,
            isShowEndline: true,
            jobList: [],
            currentPage: 0
        })
        // console.log(this.data.dropdownValue3)
        let order = 'asc'
        if (this.data.dropdownValue3 === 1) {
            order = 'desc'
        }
        this.setData({orderBy: 'salary', order})
        // 为空，不搜索
        if(!this.data.isShowEndline) {
            this.setData({
                loading: false
            })
            return
        }
        this.searchResult('salary', order).then(()=>{
            this.setData({
                loading: false
            })
        })
    },

    // 选择城市
    async confirmCity(e) {
        if (e.currentTarget.dataset.city) {
            this.setData({
                pickCity: e.currentTarget.dataset.city
            })
        } else {
            this.setData({
                pickCity: e.detail.values[2].name
            })
        }
        // 更新城市搜索记录
        console.log(this.data.preCity)
        this.data.preCity.unshift(this.data.pickCity)
        const preCity = [...new Set(this.data.preCity)]
        this.setData({preCity: preCity})
        wx.setStorageSync('searchPrecity', this.data.preCity)
        this.setData({
            loading: true,
            isShowEndline: true,
            jobList: [],
            currentPage: 0
        })
        this.setData({ showCityPicker: false })
        await this.searchResult()
        this.setData({
            loading: false
        })
    },

    // 关闭操作框
    onClose() {
        this.setData({ showCityPicker: false })
    },

    // 打开操作框
    toPickCity() {
        this.getLocation()
        this.confirmCurCityNum()
        this.setData({ showCityPicker: true })
    },

    // 点击工作详情
    toJobDetailPage(e) {
        console.log(e.currentTarget.dataset.id)
        wx.navigateTo({
            url: '/pages/job-detail/job-detail?id=' + e.currentTarget.dataset.id
        })
    },

    // 获取当前位置信息
    getLocation() {
        if (this.data.isGetCurCity) {
            return
        }
        wx.getLocation({ // 获取当前位置
          type: 'gcj02' // gcj02火星坐标系，用于地图标记点位
        }).then(async res=> { // 获取成功
            const {latitude, longitude} = res // 如果传入为空，则使用data内数据
            console.log("经纬度：" + longitude + ", " + latitude)
            await app.call({ // 发起云函数请求
                    name: 'location', // 业务为location，获取经纬度信息
                    data: { // 传入经纬度信息
                    location: `${latitude},${longitude}`
                },
                load: false // 不显示加载loading，静默执行
            }).then(res=>{
                this.setData({
                    curCity: res.adinfo.split(',')[3],
                    isGetCurCity: true
                })
            })
          }).catch(e=>{
            console.log(e)
            // 获取失败
            wx.showToast({
                title: '获取当前定位失败',
                icon: 'none'
            })
            setTimeout(() => {
                wx.hideToast()
            }, 800)
          })
    },

     // 确定地区所属区号
    confirmCurCityNum() {
        let obj = this.data.areaList.county_list
        let findKey = (value, compare = (a, b) => a === b) =>{
            return Object.keys(obj).find(k => compare(obj[k], value))
        }
        const pickCityNum = findKey(this.data.pickCity)
        this.setData({curCityNum: pickCityNum})
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            pickCity: options.city,
            keyword: options.keyword
        })
        this.searchResult().then(()=>{
            this.setData({
                loading: false
            })
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if(wx.getStorageSync('searchPrecity')) {
            this.setData({
                preCity: wx.getStorageSync('searchPrecity')
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        wx.showNavigationBarLoading()
        setTimeout(() => {
            wx.hideNavigationBarLoading()
            // 数据成功后，停止下拉刷新
            wx.stopPullDownRefresh()
        }, 600);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    async onReachBottom() {
        wx.showLoading({
            title: '加载中..',
        })
        this.data.currentPage += 1
        console.log(this.data.orderBy, this.data.order)
        if (this.data.orderBy && this.data.order) {
            await this.searchResult(this.data.orderBy, this.data.order)
        } else {
            await this.searchResult()
        }
        // 数据成功后，停止下拉刷新
        wx.stopPullDownRefresh()
        wx.hideLoading()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})